package com.core.cloudbusiness.system.user.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.cloudbusiness.system.user.mapper.CloudSystemUserMapper;
import com.core.cloudbusiness.system.user.service.CloudSystemUserService;
import com.core.cloudcommon.CommonCustomException;
import com.core.cloudcommon.CommonPageResponse;
import com.core.cloudcommon.security.PasswordValidator;
import com.core.cloundbusinessapi.system.user.dto.CloudSystemUserDTO;
import com.core.cloundbusinessapi.system.user.enums.CloudSystemUserResultCode;
import com.core.cloundbusinessapi.system.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author =====Lqj=====
 * @className CloudSystemUserServiceImpl
 * @description
 * @create 2024/11/14 16:36
 **/
@Slf4j
@Service
public class CloudSystemUserServiceImpl implements CloudSystemUserService {

    @Autowired
    private CloudSystemUserMapper cloudSystemUserMapper;

    private Snowflake snowflake = IdUtil.createSnowflake(0L, 0L);

    @Override
    public CloudSystemUserDTO add(CloudSystemAddUserVO cloudSystemUserVO) {
        if (Objects.isNull(cloudSystemUserVO)) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100001.getCode(), CloudSystemUserResultCode.CODE100001.getMsg());
        }
        log.info("云系统添加账号请求参数：\n" + JSON.toJSONString(cloudSystemUserVO));

        // 手机号格式验证
        if (cloudSystemUserVO.getPhone() == null || !cloudSystemUserVO.getPhone().matches("^1[3-9]\\d{9}$")) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100003.getCode(),
                                          "手机号格式不正确");
        }

        // 密码强度验证
        PasswordValidator.validatePassword(cloudSystemUserVO.getPassWord());
        CloudSystemQueryListUserVO cloudSystemQueryListUserVO = new CloudSystemQueryListUserVO();
        BeanUtils.copyProperties(cloudSystemUserVO, cloudSystemQueryListUserVO);
        List<CloudSystemUserDTO> cloudSystemUserDTOS = cloudSystemUserMapper.selectSysUser(cloudSystemQueryListUserVO);
        if (!cloudSystemUserDTOS.isEmpty()) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100002.getCode(), CloudSystemUserResultCode.CODE100002.getMsg());
        }
        CloudSystemUserDTO cloudSystemUserDTO = new CloudSystemUserDTO();
        BeanUtils.copyProperties(cloudSystemUserVO, cloudSystemUserDTO);
        Long id = snowflake.nextId();
        cloudSystemUserDTO.setId(id);
        cloudSystemUserDTO.setUserName("AUT-" + id);
        String salt = random();
        cloudSystemUserDTO.setSalt(salt);
        cloudSystemUserDTO.setPassWord(SecureUtil.md5(cloudSystemUserVO.getPassWord() + salt));
        cloudSystemUserDTO.setCreateBy("admin");
        Date date = new Date();
        cloudSystemUserDTO.setCreateTime(date);
        cloudSystemUserDTO.setUpdateBy("admin");
        cloudSystemUserDTO.setUpdateTime(date);
        cloudSystemUserMapper.insert(cloudSystemUserDTO);
        log.info("云系统添加账号返回参数：\n" + JSON.toJSONString(cloudSystemUserDTO));
        return cloudSystemUserDTO;

    }

    @Override
    public List<CloudSystemUserDTO> queryList(CloudSystemQueryListUserVO cloudSystemQueryListUserVO) {
        if (Objects.isNull(cloudSystemQueryListUserVO)) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), CloudSystemUserResultCode.CODE100010.getMsg());
        }
        log.info("用户list查询请求参数：\n" + JSON.toJSONString(cloudSystemQueryListUserVO));
        try {
            List<CloudSystemUserDTO> cloudSystemUserDTOS = cloudSystemUserMapper.selectSysUser(cloudSystemQueryListUserVO);
            log.info("用户list查询返回数据：\n" + JSON.toJSONString(cloudSystemUserDTOS));
            return cloudSystemUserDTOS;
        } catch (Exception e) {
            log.error("用户list查询异常信息：\n" + e);
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100011.getCode(), CloudSystemUserResultCode.CODE100011.getMsg());
        }
    }

    @Override
    public void updateLogTime(Long id) {
        if (null == id) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE1000020.getCode(), CloudSystemUserResultCode.CODE1000020.getMsg());
        }
        cloudSystemUserMapper.updateLoginTime(id);

    }

    @Override
    public CommonPageResponse findPage(CloudSystemQueryListUserVO params) {
        CommonPageResponse commonPageResponse = new CommonPageResponse();
        Page<CloudSystemUserDTO> page = new Page<>(params.getPageNumber(), params.getPageSize());
        LambdaQueryWrapper<CloudSystemUserDTO> query = Wrappers.lambdaQuery(CloudSystemUserDTO.class);
        query.orderByDesc(CloudSystemUserDTO::getCreateTime);
        Page<CloudSystemUserDTO> cloudSystemUserDTOPage = cloudSystemUserMapper.selectPage(page, query);
        commonPageResponse.setCurrent(cloudSystemUserDTOPage.getCurrent());
        commonPageResponse.setSize(cloudSystemUserDTOPage.getSize());
        commonPageResponse.setTotal(cloudSystemUserDTOPage.getTotal());
        commonPageResponse.setData(cloudSystemUserDTOPage.getRecords());
        return commonPageResponse;
    }


    @Override
    public CloudSystemUserDTO findById(String id) {
        return cloudSystemUserMapper.selectById(id);
    }


    @Override
    public Integer update(CloudSystemQueryListUserVO vo) {
        CloudSystemUserDTO cloudSystemUserDTO = new CloudSystemUserDTO();
        BeanUtils.copyProperties(cloudSystemUserDTO, vo);
        return cloudSystemUserMapper.updateById(cloudSystemUserDTO);
    }

    @Override
    public Integer delete(String id) {
        return cloudSystemUserMapper.deleteById(id);
    }


    /**
     * 随机取5个字母
     *
     * @return
     */
    private String random() {
        // 创建随机数生成器
        Random random = new Random();
        // 存储结果的列表
        List<Character> letters = new ArrayList<>(16);
        // 生成3个小写字母（a-z）
        for (int i = 0; i < 3; i++) {
            char lowerCase = (char) ('a' + random.nextInt(26));
            letters.add(lowerCase);
        }
        // 生成2个大写字母（A-Z）
        for (int i = 0; i < 2; i++) {
            char upperCase = (char) ('A' + random.nextInt(26));
            letters.add(upperCase);
        }
        // 随机打乱字母顺序
        char a = '@';
        letters.add(a);
        char b = '&';
        letters.add(b);

        Collections.shuffle(letters);
        // 将列表中的字母拼接成一个字符串
        StringBuilder sb = new StringBuilder();
        for (char letter : letters) {
            sb.append(letter);
        }
        return sb.toString();
    }

    @Override
    public CloudSystemUserDTO register(CloudSystemRegisterVO vo) {
        if (vo == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100001.getCode(), "注册参数为空");
        }
        if (vo.getPhone() == null || !vo.getPhone().matches("^1[3-9]\\d{9}$")) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100003.getCode(), "手机号格式不正确");
        }
        PasswordValidator.validatePassword(vo.getPassWord());
        CloudSystemQueryListUserVO query = new CloudSystemQueryListUserVO();
        query.setPhone(vo.getPhone());
        List<CloudSystemUserDTO> exists = cloudSystemUserMapper.selectSysUser(query);
        if (!exists.isEmpty()) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100002.getCode(), "该手机号已注册");
        }
        CloudSystemUserDTO user = new CloudSystemUserDTO();
        Long id = snowflake.nextId();
        user.setId(id);
        user.setUserName(vo.getUserName() != null ? vo.getUserName() : ("U" + id));
        user.setRealName(vo.getRealName());
        user.setEmail(vo.getEmail());
        user.setPhone(vo.getPhone());
        user.setDepartId(vo.getDepartId());
        user.setDepartName(vo.getDepartName());
        user.setSex(vo.getSex());
        user.setAvatar(vo.getAvatar());
        String salt = random();
        user.setSalt(salt);
        user.setPassWord(SecureUtil.md5(vo.getPassWord() + salt));
        Date now = new Date();
        user.setCreateBy("register");
        user.setCreateTime(now);
        user.setUpdateBy("register");
        user.setUpdateTime(now);
        cloudSystemUserMapper.insert(user);
        return user;
    }

    @Override
    public boolean changePassword(Long userId, CloudSystemChangePasswordVO vo) {
        if (userId == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), "用户未登录");
        }
        if (vo == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100001.getCode(), "参数为空");
        }
        CloudSystemUserDTO user = cloudSystemUserMapper.selectById(userId);
        if (user == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), "用户不存在");
        }
        String oldCipher = SecureUtil.md5(vo.getOldPassword() + user.getSalt());
        if (!oldCipher.equals(user.getPassWord())) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100011.getCode(), "旧密码不正确");
        }
        PasswordValidator.validatePassword(vo.getNewPassword());
        String newCipher = SecureUtil.md5(vo.getNewPassword() + user.getSalt());
        user.setPassWord(newCipher);
        user.setUpdateBy("self");
        user.setUpdateTime(new Date());
        cloudSystemUserMapper.updateById(user);
        return true;
    }

    @Override
    public boolean resetPassword(CloudSystemResetPasswordVO vo) {
        if (vo == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100001.getCode(), "参数为空");
        }
        CloudSystemQueryListUserVO query = new CloudSystemQueryListUserVO();
        query.setPhone(vo.getPhone());
        List<CloudSystemUserDTO> users = cloudSystemUserMapper.selectSysUser(query);
        if (users.isEmpty()) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), "用户不存在");
        }
        CloudSystemUserDTO user = users.get(0);
        PasswordValidator.validatePassword(vo.getNewPassword());
        String newCipher = SecureUtil.md5(vo.getNewPassword() + user.getSalt());
        user.setPassWord(newCipher);
        user.setUpdateBy("reset");
        user.setUpdateTime(new Date());
        cloudSystemUserMapper.updateById(user);
        return true;
    }

    @Override
    public CloudSystemUserDTO getProfile(Long userId) {
        if (userId == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), "用户未登录");
        }
        return cloudSystemUserMapper.selectById(userId);
    }

    @Override
    public CloudSystemUserDTO updateProfile(Long userId, CloudSystemUpdateProfileVO vo) {
        if (userId == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), "用户未登录");
        }
        CloudSystemUserDTO user = cloudSystemUserMapper.selectById(userId);
        if (user == null) {
            throw new CommonCustomException(CloudSystemUserResultCode.CODE100010.getCode(), "用户不存在");
        }
        if (vo.getUserName() != null) user.setUserName(vo.getUserName());
        if (vo.getRealName() != null) user.setRealName(vo.getRealName());
        if (vo.getEmail() != null) user.setEmail(vo.getEmail());
        if (vo.getPhone() != null) user.setPhone(vo.getPhone());
        if (vo.getSex() != null) user.setSex(vo.getSex());
        if (vo.getAvatar() != null) user.setAvatar(vo.getAvatar());
        user.setUpdateBy("self");
        user.setUpdateTime(new Date());
        cloudSystemUserMapper.updateById(user);
        return user;
    }


}
